<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class RegisterForm extends CFormModel
{
	public $username;
	public $password;
	public $email;
	public $passwordTow;
	public $create_time;
	public $rememberMe;
	public $checkRules;
	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('username, password,passwordTow,email', 'required','message'=>'不能为空'),
			// rememberMe needs to be a boolean
			array('email','email','message'=>'邮箱格式不对'),
			array('email','authenticate'),
			array('rememberMe', 'boolean'),
			array('passwordTow','compare','compareAttribute'=>'password','message'=>'两次密码不一致'),
			array('password','length','min'=>6,'max'=>100,'message'=>'密码长度不能低于6位'),
			array('checkRules','compare','compareValue'=>1,'message'=>'请阅读使用协议'),
			// password needs to be authenticated
			//array('password', 'authenticate'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'rememberMe'=>'Remember me next time',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{			
			$user = User::model()->findByAttributes(array('email'=>$this->email));
			if($user!=null)
			{
				$this->addError('email','邮箱已注册');
			}
		}
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			if(!$this->_identity->authenticate())
				$this->addError('password','请输入正确的用户名和密码');
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			Yii::app()->user->setReturnUrl(Yii::app()->createUrl('profile/index'));
			return true;
		}
		else
			return false;
	}

}
